<template>
    <div>
        <a-form style="margin-top: 10px;margin-left: 5px;" :layout="'inline'">
            <a-form-item label="手机号">
                <a-input v-model:value="searchParams.mobile" placeholder="请输入手机号" allowClear/>
            </a-form-item>
            <a-form-item label="用户名">
                <a-input v-model:value="searchParams.username" placeholder="请输入用户名" allowClear/>
            </a-form-item>
            <a-form-item>
                <a-button @click="search" type="primary">
                    <template #icon>
                        <SearchOutlined/>
                    </template>
                    搜索
                </a-button>
                <a-button @click="resetSearch" class="main_rest">
                    <template #icon>
                        <SyncOutlined/>
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-form>
        <div class="main_operation">
            <a-button @click="handleAdd" class="main_operation_item" type="primary">
                新增
                <template #icon>
                    <PlusOutlined/>
                </template>
            </a-button>
            <a-button @click="handleEdit" :disabled="single" class="main_operation_edit">
                <template #icon>
                    <EditTwoTone/>
                </template>
                修改
            </a-button>
            <a-button @click="handleDelete" :disabled="multiple" class="main_operation_item" type="primary" danger>
                <template #icon>
                    <DeleteTwoTone/>
                </template>
                删除
            </a-button>
            <a-button @click="handleExportSysUser" class="main_operation_export">
                <template #icon>
                    <VerticalAlignBottomOutlined/>
                </template>
                导出
            </a-button>
        </div>

        <a-table :row-selection="rowSelection" :columns="columns" :data-source="userList" :pagination="pagination"
                 row-key="id" style="word-break: break-all;">
            <template v-slot:bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'operation'">
                    <div>
          <span>
            <a-button @click="handleEdit(record.id)" class="main_operation_button" type="primary" ghost>修改</a-button>
            <a-button v-if="record.status==='0'" @click="handleDelete(record)" class="main_operation_button"
                      danger>禁用</a-button>
            <a-button v-else @click="handleRelieve(record.id)" class="main_operation_button"
                      type="primary">启用</a-button>
          </span>
                    </div>
                </template>
            </template>
        </a-table>

        <!-- 新增或修改对话框 -->
        <a-modal
                ref="modalRef"
                v-model:visible="visible"
                @ok="handleOk"
                cancelText="取消"
                okText="确认"
        >
            <a-form :label-col="{ span: 4 }">
                <a-form-item label="手机号" v-bind="validateInfos.mobile">
                    <a-input v-model:value="userinfo.mobile" placeholder="请输入手机号"/>
                </a-form-item>
                <a-form-item label="密码" v-bind="validateInfos.password">
                    <a-input v-model:value="userinfo.password" type="password" placeholder="请输入密码"/>
                </a-form-item>
                <a-form-item label="用户名" v-bind="validateInfos.username">
                    <a-input v-model:value="userinfo.username" type="username" placeholder="请输入用户名"/>
                </a-form-item>
            </a-form>
            <template #title>
                <div ref="modalTitleRef" style="width: 100%; cursor: move">{{ title }}</div>
            </template>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import {TableColumnType, message, Form} from 'ant-design-vue';
import {
    PlusOutlined,
    EditTwoTone,
    DeleteTwoTone,
    VerticalAlignBottomOutlined,
    SyncOutlined,
    SearchOutlined
} from '@ant-design/icons-vue';
import {reactive, ref} from "vue";
import {
    addSysUser,
    deleteSysUser,
    exportSysUser,
    getSysUser,
    getSysUserList,
    relieveSysUser,
    searchSysUser, updateSysUser
} from "@/api/user/sysUser";

interface DataType {
    key: string;
    id: number;
}

//标签
const columns: TableColumnType<DataType>[] = [
    {
        title: '手机号',
        align: "center",
        dataIndex: 'mobile',
    },
    {
        title: '用户名',
        align: "center",
        dataIndex: 'username',
    },
    {
        title: '账号状态',
        align: "center",
        dataIndex: 'status',
    },
    {
        title: '创建时间',
        align: "center",
        dataIndex: 'createTime',
    },
    {
        title: '更新时间',
        align: "center",
        dataIndex: 'updateTime',
    },
    {
        title: 'ip',
        align: "center",
        dataIndex: 'ip',
    },
    {
        title: '地址',
        align: "center",
        width: 200,
        dataIndex: 'address',
    },
    {
        title: '操作',
        align: "center",
        dataIndex: 'operation',
    },
];

//选中的id数组
const ids = ref<number[]>([])
//非单个禁用
const single = ref<boolean>(true)
//是否多选
const multiple = ref<boolean>(true)

//多选框
const rowSelection = {
    onChange: (selectedRowKeys: string[], selectedRows: DataType[]) => {
        ids.value = selectedRows.map(item => item.id)
        single.value = ids.value.length !== 1
        multiple.value = !ids.value.length
    }
};

//是否显示修改对话框
const visible = ref<boolean>(false);
//对话框标题
const title = ref("")

//用户信息
const userinfo = ref({
    id: '',
    mobile: '',
    password: '',
    username: '',
    status: '',
})

//表单校验
const rulesRef = reactive({
    password: [
        {
            required: true,
            message: '请输入密码',
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入手机号',
        },
        {
            len: 11,
            whitespace: true,
            message: '手机号必须为11位',
            trigger: 'blur',
        },
        {
            pattern: /^1[3-9]\d{9}$/,
            whitespace: true,
            message: '手机号格式不正确',
            trigger: 'blur',
        },
    ],
    username: [
        {
            required: true,
            message: '请输入用户名',
        }
    ],
});

const useForm = Form.useForm;
const {validate, validateInfos} = useForm(userinfo, rulesRef);

//用户列表
const userList = ref()

//分页参数
const pagination = ref({
    size: 'large',
    current: 1,//当前页
    pageSize: 10,//每页数量
    total: 0,//总页数
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total: number) => {
        return " 共" + total + "条"
    },
    showSizeChanger: true,
    onShowSizeChange: (current: number, pageSize: number) => {
        pagination.value.pageSize = pageSize
        search()
    },
    onChange: (current: number) => {
        pagination.value.current = current
        search()
    }
})

//搜索参数
const searchParams = ref({
    mobile: '',
    username: '',
})

//获取所有用户
const handleSysUserList = () => {
    getSysUserList(pagination.value.current, pagination.value.pageSize).then((res) => {
        userList.value = res.data.data.map.list
        pagination.value.total = res.data.data.map.total
    })
}

//修改用户
const handleEdit = async (id: number) => {
    reset()
    const userId: any = ids.value[0] || id
    const res = await getSysUser(userId)
    userinfo.value = res.data.data.sysUser
    if (userinfo.value.status === '1') {
        message.warning('请先启用用户');
    } else {
        visible.value = true
        title.value = "修改用户信息"
    }
}

//新增用户
const handleAdd = () => {
    reset()
    visible.value = true
    title.value = "新增用户信息"
}

//禁用用户
const handleDelete = (row: any) => {
    const userIds: any = row.id || ids.value
    deleteSysUser(userIds).then((res) => {
        message.success(res.data.message)
        handleSysUserList()
    })
}

//解禁用户
const handleRelieve = (id: number) => {
    relieveSysUser(id).then((res) => {
        message.success(res.data.message)
        handleSysUserList()
    })
}

//新增或修改提交按钮
const handleOk = () => {
    validate().then(() => {
        if (userinfo.value.id != '') {
            updateSysUser(userinfo.value).then((res) => {
                if (res.data.code === 400) {
                    message.warn(res.data.message)
                } else {
                    visible.value = false;
                    handleSysUserList()
                }
            })
        } else {
            addSysUser(userinfo.value).then((res) => {
                if (res.data.code === 400) {
                    message.warn(res.data.message)
                } else {
                    visible.value = false;
                    handleSysUserList()
                }
            })
        }
    }).catch(err => {
        console.log('error', err);
    });
}

//搜索表单重置
const resetSearch = () => {
    searchParams.value.mobile = ''
    searchParams.value.username = ''
    handleSysUserList()
}

//用户信息重置
const reset = () => {
    userinfo.value.mobile = ''
    userinfo.value.password = ''
    userinfo.value.username = ''
}

//搜索
const search = () => {
    searchSysUser(searchParams.value).then((res) => {
        userList.value = res.data.data.list
        pagination.value.total = res.data.data.list.length
    })
}

//导出
const handleExportSysUser = () => {
    exportSysUser().then((response) => {
        message.success("导出成功")
        let blob = new Blob([response.data], {
            //要与后端对应
            type: 'application/vnd.ms-excel'
        });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '系统用户信息.xlsx';
        link.click();
        //释放内存
        window.URL.revokeObjectURL(link.href)
    })
}

handleSysUserList()
</script>

<style lang="less" scoped>
.main_operation {
  margin: 10px;
  display: flex;

  .main_operation_item {
    margin-right: 10px;
  }

  .main_operation_edit {
    background-color: palegreen;
    margin-right: 10px;
  }

  .main_operation_export {
    background-color: sandybrown;
    margin-right: 10px;
  }
}

.main_rest {
  margin-left: 5px;
}

.main_operation_button {
  margin: 5px;
}

:deep(.ant-form-item-control-input-content) {
  margin-bottom: 5px;
}
</style>